#include "head.h"

int read_config(const char *file_name,config *config_info) {
    //打开配置文件
    FILE *file_fd = fopen(file_name,"r");
    if(file_fd == NULL) {
        LOG(ERROR,"文件打开失败");
        return 0;
    }
    
    char category[CONFIG_MAX_LEN] = {0};
    char *per_line = (char *)calloc(CONFIG_MAX_LEN,sizeof(char));  
    //按行读取数据
    while(fgets(per_line,CONFIG_MAX_LEN * sizeof(char),file_fd) != NULL) {
        //跳过注释、空行
        if(per_line[0] == '#' || per_line[0] == ';' || per_line[0] == '\n') {
                continue;
        }

        //清除换行符
        per_line[strcspn(per_line,"\n")] = 0;
        //配置的类型
        if(per_line[0] == '[') {
            bzero(category,sizeof(category));
            strncpy(category,per_line + 1,strcspn(per_line,"]") - 1);
            continue;
        }
        
        //配置的键值对
        char key[CONFIG_MAX_LEN] = {0};
        char value[CONFIG_MAX_LEN] = {0};
        
        //找到键值对的‘=’位置
        int index = strcspn(per_line,"=");
        
        strncpy(key,per_line,index - 1);
        strncpy(value,per_line + index + 2, strlen(per_line));
        
        if(strcmp(category,"log") == 0) {
                if(strcmp(key,"path") == 0) {
                    strcpy(config_info -> log_path,value);
                }
        } else if(strcmp(category,"server") == 0) {
                 if(strcmp(key,"ip") == 0) {
                    strcpy(config_info -> server_ip,value);
                } else if(strcmp(key,"port") == 0) {
                    strcpy(config_info -> server_port,value);
                }
        } else if(strcmp(category,"database") == 0) {
            if(strcmp(key,"user") == 0) {
                strcpy(config_info -> data_base_user,value);
            } else if(strcmp(key,"password") == 0) {
                strcpy(config_info -> data_base_pwd,value);
            } else if(strcmp(key,"data_base") == 0) {
                strcpy(config_info -> data_base_name,value);
            }
        } else if(strcmp(category,"pthread") == 0) {
            if(strcmp(key,"count") == 0) {
                config_info -> pthread_count = (value[0] - '0');
            }
        }
        bzero(per_line,CONFIG_MAX_LEN * sizeof(char));
    }
    free(per_line);
    fclose(file_fd);
    return 1;
}


